#pragma once

#include <iostream>
#include "Mutex.hpp"
#include <string>
#include <filesystem>
#include <fstream>
#include <ctime>
#include <unistd.h>
#include<memory>
// 规定出常见的日志等级
enum class Loglevel
{
    DEBUG,
    INFO, // 常规输出
    WARNING,
    ERROR,
    FATAL
};

// 日志等级转换为字符串
std::string LeveltoString(Loglevel level)
{
    switch (level)
    {
    case Loglevel::DEBUG:
        return "Debug";
    case Loglevel::INFO:
        return "Info";
    case Loglevel::WARNING:
        return "Warning";
    case Loglevel::ERROR:
        return "Error";
    case Loglevel::FATAL:
        return "Fatal";
    default:
        return "Unkown";
    }
}
std::string GetCurrentTime()
{
    // 无符号整数
    time_t currtime = time(nullptr);

    // 时间戳转化成时间
    struct tm currtm;
    localtime_r(&currtime, &currtm);

    // 转化成为字符串
    char timebuffer[64];
    snprintf(timebuffer, sizeof(timebuffer), "%4d-%02d-%02d %02d:%02d:%02d",
             currtm.tm_year + 1900, currtm.tm_mon + 1, currtm.tm_mday, currtm.tm_hour, currtm.tm_min, currtm.tm_sec);

    // struct tm {
    //            int tm_sec;    /* Seconds (0-60) */
    //            int tm_min;    /* Minutes (0-59) */
    //            int tm_hour;   /* Hours (0-23) */
    //            int tm_mday;   /* Day of the month (1-31) */
    //            int tm_mon;    /* Month (0-11) */
    //            int tm_year;   /* Year - 1900 */
    //            int tm_wday;   /* Day of the week (0-6, Sunday = 0) */
    //            int tm_yday;   /* Day in the year (0-365, 1 Jan = 0) */
    //            int tm_isdst;  /* Daylight saving time */
    //        };

    return timebuffer;
}

// 日志刷新
class LogStrategy
{
public:
    virtual ~LogStrategy() = default;
    virtual void SyncLog(const std::string &logmessage) = 0;
};

// 显示器刷新
class ConsoleLogStrategy : public LogStrategy
{
public:
    ~ConsoleLogStrategy()
    {
    }
    void SyncLog(const std::string &logmessage) override
    {
        {
            LockGuard lockguard(&_lock);
            std::cout << logmessage << std::endl;
        }
    }

private:
    Mutex _lock;
};
// 文件刷新
const std::string logdefaultdir = "log";
const static std::string logfilename = "test.log";
class FileLogStrategy : public LogStrategy
{
public:
    FileLogStrategy(const std::string &dir = logdefaultdir, const std::string filename = logfilename)
        : _dir_path_name(dir), _filename(filename)
    {
        LockGuard lockguard(&_lock);
        // 创建目录
        if (std::filesystem::exists(dir))
        {
            return;
        }
        try
        {
            std::filesystem::create_directories(_dir_path_name);
        }
        catch (const std::filesystem::filesystem_error &e)
        {
            std::cerr << e.what() << "\r\n";
        }
    }
    void SyncLog(const std::string &logmessage) override
    {
        {
            LockGuard LockGuard(&_lock); // 串行刷新信息，保证不要信息错乱
            std::string target = _dir_path_name;
            target += "/";
            target += _filename;

            std::ofstream out(target.c_str(), std::ios::app); // append
            if (!out.is_open())
            {
                return;
            }
            out << logmessage << "\n"; // out.write
            out.close();
        }
    }
    ~FileLogStrategy()
    {
    }

private:
    std::string _dir_path_name;
    std::string _filename;
    Mutex _lock;
};

class Logger
{
public:
    Logger()
    {
    }
    void EnableConsoleLogSrategy()
    {
        _strategy = std::make_unique<ConsoleLogStrategy>();
    }
    void EnableFileLogStrategy()
    {
        _strategy = std::make_unique<FileLogStrategy>();
    }

    // 形成一条完整日志的方式
    class LogMessage
    {
    public:
        LogMessage(Loglevel level,std::string& filename,int line,Logger& logger)
        :_curr_time(GetCurrentTime())
        ,_level(level)
        ,_pid(getpid())
        ,_filename(filename)
        ,_line(line)
        ,_logger(logger)
        {
            std::stringstream ss;//字符串流
            ss<<"["<<_curr_time<<"]"<<"["<<LeveltoString(_level)<<"] "<<"[" <<_pid<<"] "
            <<"[" <<_filename<<"] "
            <<"[" <<_line<<"] "
            <<"- ";

            _loginfo=ss.str();//左半部分
        }
        template<typename T>
        LogMessage& operator <<(const T& info)
        {
            std::stringstream ss;
            ss<<info;
            _loginfo+=ss.str();
            return *this;
        }
        ~LogMessage()
        {
            if(_logger._strategy)
            {
                _logger._strategy->SyncLog(_loginfo);//原来深秋是孤独的
            }
        }

    private:
        std::string _curr_time; // 时间
        Loglevel _level;        // 等级
        pid_t _pid;             //进程pid
        std::string _filename;
        int _line;//行号

        std::string _loginfo;//一条合并完成的，完整的日志信息
        Logger& _logger;//外部类的引用，通过这个引用把数据刷新出去，提供刷新策略的具体做法
    };//类你得加个;不然他会以为这个下面析构函数的返回值类型

    LogMessage operator()(Loglevel level,std::string filename,int line)
    {
        return LogMessage(level,filename,line,*this);//传进来logger目的是让他析构的时候做刷新
    }
    ~Logger()
    {
    }

private:
    std::unique_ptr<LogStrategy> _strategy;
};

Logger logger;

#define LOG(level) logger(level,__FILE__,__LINE__)//当前源文件的完成路径和路径名
//LINE是当前执行代码的行号
#define EnableConsoleLogSrategy() logger.EnableConsoleLogSrategy()
#define EnableFileLogStrategy() logger.EnableFileLogStrategy()
